/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.open.api.facade.order;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import info.peigen.hotpot.common.service.base.ServiceOrderBase;
import jakarta.validation.*;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;
import lombok.*;
import lombok.experimental.Accessors;
import lombok.experimental.FieldDefaults;
import lombok.experimental.SuperBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Set;

/**
 * <b>(OpenApiOrder)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2021/10/19
 */
@Slf4j
@EqualsAndHashCode(callSuper = true)
@SuperBuilder
@Data
@NoArgsConstructor
@AllArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
@Accessors(chain = true)
public class OpenApiOrder extends ServiceOrderBase {
    @NotEmpty
    @Size(max = 30)
    String requestNo;
    /** 接口名称 */
    @NotEmpty
    @Size(max = 300)
    String apiCode;
    /** 加密串 */
    @NotEmpty
    String encrypt;
    /** 客户浏览器 IP */
    @Builder.Default
    @Size(max = 20)
    String userIp  = "";
    /** 接口版本 */
    @Builder.Default
    @Size(max = 20)
    String version = "1.0";
    /** 签名 */
    @Size(max = 100)
    String sign;

    /** yyyyMMddHHmmss+abbreviation(4)+0156 */
    public static String genRequestNo(String abbreviation) {
        return DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN) + abbreviation + RandomUtil.randomNumbers(4);
    }

    /**
     * 校验参数
     */
    public void checkForSimple() {
        ValidatorFactory                 factory    = Validation.buildDefaultValidatorFactory();
        Validator                        validator  = factory.getValidator();
        Set<ConstraintViolation<Object>> violations = validator.validate(this);
        if (!violations.isEmpty()) {
            List<String> msgList = Lists.newArrayList("\n");
            for (ConstraintViolation<Object> violation : violations) {
                msgList.add(violation.getRootBeanClass()
                        .getSimpleName() + "." + violation.getPropertyPath() + ":" + violation.getMessage());
            }
            String message = StrUtil.join("\n", msgList.toArray());
            log.error("参数校验有误:{}", message);
            throw new ConstraintViolationException(message, violations);
        }
    }

}